import '@tarojs/async-await';
import Taro, { Component } from '@tarojs/taro';
import { Provider } from '@tarojs/redux';
import { set as setGlobalData, get as getGlobalData, } from './utils/globalData';
import Index from './pages/index';

import configStore from './store';

import './app.scss';
import { setting } from './services/program';
import { getSessionKey, decryptData, register, getUserInfo, getMemberPic, getMemberword } from './services/user';
import { getUserCardCount } from './services/electronicCard';
import { fullImgUrl, timeFormat } from './utils/utils';

// 如果需要在 h5 环境中开启 React Devtools
// 取消以下注释：
// if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5')  {
//   require('nerv-devtools')
// }

const store = configStore();

class App extends Component {
  config = {
    pages: [
      'pages/home/index',
      'pages/activity/index',
      'pages/index/index',
      'pages/user/index',
      'pages/goods-detail/index',
      'pages/my-order/index',
      'pages/info/index',
      'pages/sweep/index',
      'pages/vip-list/index',
    ],
    subPackages: [
      {
        root: 'subPackageWork',
        pages: [
          'pages/user-roll/index',
          'pages/roll-shop-list/index',
          'pages/user-roll-time/index',
          'pages/agency-performance/index',
          'pages/webView/index',
          'pages/express-status/index',
          'pages/storage-record/index',
          'pages/storage-success/index',
          'pages/output/index',
          'pages/choose-agency/index',
          'pages/customized/index',
          'pages/customizeds/index',
          'pages/goods-list/index',
          'pages/apply-invoice/index',
          'pages/order-detail/index',
          'pages/settlement/index',
          'pages/edit-info/index',
          'pages/card-record/index',
          'pages/used-card-record/index',
          'pages/apply/index',
          'pages/apply-member-card/index',
          'pages/apply-success/index',
          'pages/activate-card/index',
          'pages/performance/index',
          'pages/agency/index',
          'pages/shop-list/index',
          'pages/my-address/index',
          'pages/edit-address/index',
          'pages/login/index',
          'pages/exchange/index',
          'pages/agent_customizes/index',
          'pages/coupon-exchange/index',
          'pages/coupon-list/index',
          'pages/electronic-card/index',
          'pages/electronic-lp/index',
          'pages/electronic-settlement/index',
        ],
      },
      {
        root: 'subPacKagebWork',
        pages: [
          'pages/camera/index',
          'pages/bangdingcard/index',
          'pages/bindingcard/index',
          'pages/vip-goods-list/index',
          'pages/settlement-center/index',
          'pages/settlement-centers/index',
          'pages/vidioplay/index',
          'pages/agent-list/index',
          'pages/vip-record-all/index',
          'pages/edit-agent-list/index',
          'pages/cart/index',
          'pages/vip-record/index',
          'pages/turnove-record/index',
          'pages/agentremarks/index',
          'pages/agent-remarks/index',
          'pages/batch-apply-invoice/index',
          'pages/apply-invoice/index',
          'pages/my-apply-invoice/index',
          'pages/agent-Datasta/index',
          'pages/edit-apply-invoice/index',
          'pages/settlement/index',
        ],
      },
    ],
    window: {
      backgroundTextStyle: 'light',
      navigationBarTitleText: 'WeChat',
      navigationStyle: 'custom',
    },
  };

  state = {};

  componentDidMount() {
    const system = Taro.getSystemInfoSync();
    if (system.platform.indexOf('android') === -1) {
      system.titleBarHeight = 44;
    } else {
      system.titleBarHeight = 48;
    }
    Taro.setStorageSync('system', system);
    Taro.setStorageSync(
      'navigationBarHeight',
      system.titleBarHeight + system.statusBarHeight + 'px'
    );
    Taro.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          Taro.login({
            success: function (res) {
              Taro.getUserInfo({
                success: function (userInfo) {
                  // 获取session-key
                  getSessionKey({ code: res.code }).then(keyRes => {
                    // 解密
                    let data = {
                      encryptedData: userInfo.encryptedData,
                      iv: userInfo.iv,
                      key: keyRes.key,
                    };
                    decryptData(data).then(decryptRes => {
                      Taro.setStorageSync('openId', decryptRes.openId);
                      let unionId = '';
                      if (decryptRes.unionId) {
                        unionId = decryptRes.unionId;
                      }
                      // 用户登录
                      let data = {
                        type: 1,
                        nickname: userInfo.userInfo.nickName,
                        openid: decryptRes.openId,
                        avatar: userInfo.userInfo.avatarUrl,
                        unionid: unionId,
                      };
                      register(data).then(res => {
                        Taro.setStorageSync('isGetScopeUserInfo', 'true');
                        setGlobalData('token', res.token);
                        Taro.setStorageSync('token', res.token);
                        Taro.hideLoading();
                        res.user.avatar = fullImgUrl(res.user.avatar);
                        res.user.create_time = timeFormat(res.user.create_time, 'yyyy年MM月dd日');
                        const { user, user_oauth: oauth } = res;
                        user.user_oauth = oauth;
                        Taro.setStorageSync('userInfo', user);
                        setGlobalData('userInfo', user);

                        getUserCardCount().then((res) => {
                          // 设置电子卡券数量，以判断是否展示 红点
                          Taro.setStorageSync('card_count', res.total);
                          Taro.setStorageSync('will_expire_card_count', res.will_expire);
                        });
                      });
                    });
                  });
                },
              });
            },
          });
        } else {
          console.log('用户还未授权登录');
          // 限制强制登录
          Taro.navigateTo({
            url: '/subPackageWork/pages/login/index'
          });
        }
      },
    });
    setting().then(res => {
      Taro.setStorageSync('setting', res);
      setGlobalData('setting', res);
    });
    getMemberPic().then(res => {
      Taro.setStorageSync('MemberPic', res);
      setGlobalData('MemberPic', res);
    });
    getMemberword().then(res => {
      Taro.setStorageSync('Memberword', res);
      setGlobalData('Memberword', res);
    });
  }

  componentWillMount() {

  }

  componentDidShow() { }

  componentDidHide() { }

  componentDidCatchError() { }

  // 在 App 类中的 render() 函数没有实际作用
  // 请勿修改此函数
  render() {
    return (
      <Provider store={store}>
        <Index />
      </Provider>
    );
  }
}

Taro.render(<App />, document.getElementById('app'));
